#coding:utf8
from __future__ import unicode_literals

from django.db import models
from django.core.urlresolvers import reverse_lazy
# Create your models here.
from django.contrib.auth.models import User,Group
class Menu(models.Model):
    """
    菜单
    URL 格式  /app_name/model_name/operation_name(classname)/?参数
    """
    text = models.CharField('菜单名', max_length=100, help_text='最多100个英文字母长')
    parent_id = models.IntegerField('父ID',blank=True,default=0)
    namespace = models.CharField('APP名', max_length=100)
    url_name = models.CharField('view名', max_length=100)
    addition = models.CharField('附加参数', max_length=200, blank=True)
    is_system = models.BooleanField('是否为系统菜单', default=False, blank=True, \
                                    help_text='系统菜单只对超级用户和后台用户显示')
    checked = models.BooleanField('是否默认显示', default=False, help_text='勾选，默认显示')

    def __str__(self):
        return self.text

    def save(self, *args, **kwargs):
        parent_id = self.parent_id
        if parent_id is None  or parent_id=="":
            self.parent_id=0
        super(Menu, self).save(*args, **kwargs)





class MyUserMenu( models.Model):
    """
    用户的菜单权限
    """
    user = models.ForeignKey(User, verbose_name='用户')
    menus_show = models.TextField('菜单显示权限', help_text='JSON格式的字符串，在菜单显示', blank=True)
    menus_checked = models.TextField('菜单checked', help_text='JSON格式的字符串, checked用户权限配置', blank=True)
    def get_absolute_url(self):
        return reverse_lazy('menu:MyUserMenuListView')

    def __str__(self):
        return self.user

    class Meta:
        verbose_name = '用户菜单权限'
        verbose_name_plural = verbose_name
        permissions = (
            ('list_myusermenu', '查看'+verbose_name),
        )

    '''def save(self, *args, **kwargs):
        #  把多余的menus_show中重复的ID去除
        menus_show = self.menus_show
        menu_id_set =  set(menus_show.split(','))
        self.menus_show =  ','.join(menu_id_set)

        super(MyUserMenu, self).save(*args, **kwargs)
'''


class MyGroupMenu( models.Model):
    """
    用户的菜单权限
    """
    group = models.ForeignKey(Group, verbose_name='用户组')
    menus_show = models.TextField('菜单显示权限', help_text='JSON格式的字符串，在菜单显示', blank=True)
    menus_checked = models.TextField('菜单checked', help_text='JSON格式的字符串, 保留用户组checked内容', blank=True)
    def get_absolute_url(self):
        return reverse_lazy('menu:MyGroupMenuListView')

    def __str__(self):
        return unicode(self.group)

    class Meta:
        verbose_name = '用户组菜单权限'
        verbose_name_plural = verbose_name
        permissions = (
            ('list_mygroupmenu', '查看'+verbose_name),
        )

    def save(self, *args, **kwargs):
        #  把多余的menus_show中重复的ID去除
        menus_show = self.menus_show
        menu_id_set =  set(menus_show.split(','))
        self.menus_show =  ','.join(menu_id_set)

        super(MyGroupMenu, self).save(*args, **kwargs)
